﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace Hotel.Repositories
{
    public class DistributedCache<TItem> : IDistributedCache<TItem> where TItem : class
    {
        /// <summary>
        /// 缓存方法，默认有效期2天
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<List<TItem>> GetOrAddAsync(string Key, Func<Task<List<TItem>>> Value, DistributedCacheEntryOptions options = null)
        {
            IDistributedCache cache = ServiceProviderInstance.Instance.GetService(typeof(IDistributedCache)) as IDistributedCache;

            string json = await cache.GetStringAsync(Key);

            //说明缓存中无数据
            if (string.IsNullOrEmpty(json))
            {
                var list = await Value();
                //写入缓存
                if(options == null)
                {
                    options = new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddDays(2) };
                }
                await cache.SetStringAsync(Key, JsonConvert.SerializeObject(list), options);
                return list;
            }
            else
            {
                return JsonConvert.DeserializeObject<List<TItem>>(json);
            }
        }
    }
}
